package com.sbs.gaoxinqutoilet.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.ListPopupWindow;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.adapter.ToiletRebuildRvAdapter;
import com.sbs.gaoxinqutoilet.base.BaseBackFragment;
import com.sbs.gaoxinqutoilet.entity.CountyEntity;
import com.sbs.gaoxinqutoilet.entity.HomeMenuEntity;
import com.sbs.gaoxinqutoilet.entity.MessageEvent;
import com.sbs.gaoxinqutoilet.entity.ReBuildItemEntity;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.eventbus.StartNewFragmentEvent;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.interfaces.ContyPopuListener;
import com.sbs.gaoxinqutoilet.interfaces.PopuClickListener;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.NetworkUtils;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.appinstallerutils.ConvertUtils;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * Created by 聪明一只哈 on 2018/6/4.
 * Time: 2018/6/4  8:59
 */

public class ToiletRebuildFragment extends BaseBackFragment {


    //传过来的改造检查数据  存储在Bundle中
    private static final String REBUILD_BEAN = "rebuild_bean";


    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar_iv_menu)
    ImageView toolbarIvMenu;
    @BindView(R.id.toolbar_tv_menu)
    TextView toolbarTvMenu;
    @BindView(R.id.toolbar_rl_menu)
    AutoRelativeLayout toolbarRlMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_default_rebuild_order)
    TextView tvDefaultRebuildOrder;
    @BindView(R.id.et_rebuild_getcontent)
    EditText etRebuildGetcontent;
    @BindView(R.id.bt_rebuild_filter)
    Button btRebuildFilter;
    @BindView(R.id.rebuild_rv)
    RecyclerView rebuildRv;
    @BindView(R.id.rebuild_rv_trefresh)
    TwinklingRefreshLayout rebuildRvTrefresh;
    @BindView(R.id.toilet_rebuild_fl)
    AutoRelativeLayout toiletRebuildFl;
    @BindView(R.id.rebuild_search_all)
    AutoLinearLayout rebuildSearchAll;
    @BindView(R.id.all_maodian)
    AutoLinearLayout rebuildMD;
    @BindView(R.id.rebuild_address_conty)
    TextView rebuild_Tvconty;
    @BindView(R.id.rebuild_address_town)
    TextView rebuild_Tvtown;
    @BindView(R.id.rebuild_address_village)
    TextView rebuild_Tvvillage;
    @BindView(R.id.bt_rebuild_top)
    Button rebuildRebuildTop;
    Unbinder unbinder;


    private ArrayList<ReBuildItemEntity.DataBean> buyItemList;
    private ToiletRebuildRvAdapter applyRvAdapter;
    //默认排序
    List<String> userorderlist = new ArrayList<>();
    private int index;


    private View emptyView;
    private View errorView;
    private View footView;
    private RebuildDataItemRequest rebuildRequest;
    private HomeMenuEntity rebuildhomemenu_check;
    private ContyRequest cavRequest;
    private TwonRequest twonRequest;
    private VillageRequest villageRequest;
    private ListPopupWindow contyPopupWindow;

    //获取县乡村的name
    private List<String> namelist = new ArrayList<>();
    private ListPopupWindow twonPopupWindow;
    private ListPopupWindow villagePopupWindow;

    public static ToiletRebuildFragment newInstance(HomeMenuEntity homeMenuEntity) {
        Bundle args = new Bundle();
        args.putSerializable(REBUILD_BEAN, homeMenuEntity);
        ToiletRebuildFragment fragment = new ToiletRebuildFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_rebuild, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(inflater);

        initData();

        initListener();
        return attachToSwipeBack(view);
    }


    /**
     * 初始化view
     *
     * @param inflater
     */
    private void initView(LayoutInflater inflater) {
        EventBus.getDefault().register(this);
        toolbarTitle.setText("户厕改造重建");
        //返回按钮
        toolbarBack.setVisibility(View.VISIBLE);
        //设置回键
        initToolbarBack(toolbar);
//--------------------------------------------
        userorderlist.add("户     名");
        userorderlist.add("户  编  号");
        userorderlist.add("辖区单位");
//--------------------------------------------


//=======================获取传递过来的值=================================
        Bundle arguments = getArguments();
        if (arguments != null) {
            rebuildhomemenu_check = (HomeMenuEntity) arguments.getSerializable(REBUILD_BEAN);
        }
//=======================获取传递过来的值=================================

        //添加刷新头和尾
        SinaRefreshView sinaHeader = new SinaRefreshView(_mActivity);
        sinaHeader.setArrowResource(R.drawable.arrow);
        sinaHeader.setTextColor(0xff745D5C);
        rebuildRvTrefresh.setHeaderView(sinaHeader);

        LoadingView loadingView = new LoadingView(_mActivity);
        rebuildRvTrefresh.setBottomView(loadingView);
        rebuildRvTrefresh.setEnableLoadmore(false);

        //初始化index
        index = 0;
        buyItemList = new ArrayList<>();
        applyRvAdapter = new ToiletRebuildRvAdapter(R.layout.item_toilet_rebuild, buyItemList);
        rebuildRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        rebuildRv.setAdapter(applyRvAdapter);
        applyRvAdapter.disableLoadMoreIfNotFullPage(rebuildRv);

        emptyView = inflater.inflate(R.layout.view_empty, rebuildRv, false);
        errorView = inflater.inflate(R.layout.view_error, rebuildRv, false);
        footView = inflater.inflate(R.layout.view_foot, rebuildRv, false);


    }


    private void initData() {

        //获取县,乡,村级列表数据
        //获取个人信息
        UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
        if (userEntity != null) {
            //获取县级列表
            getContyList(userEntity);
        }

    }

    //县级列表
    private List<CountyEntity> contylist = null;
    //乡级列表
    private List<CountyEntity> twonlist = null;
    //村级列表
    private List<CountyEntity> villagelist = null;

    private void getContyList(UserEntity userEntity) {
        //需要拼接
        String addnew_url = HttpApis.addnew_info + userEntity.getArea_id() + "/" + "3";

        showLoadingDialog("正在加载县级数据");
        if (cavRequest == null) {
            cavRequest = new ContyRequest();
        }

        Log.i("乡级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url, cavRequest);
    }

    private void getTownList(String conty_id) {
        String addnew_url = HttpApis.addnew_info + conty_id + "/" + "4";


        if (twonRequest == null) {
            twonRequest = new TwonRequest();
        }

        Log.i("县级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url, twonRequest);

    }

    private void getVillageList(String teon_id) {
        String addnew_url = HttpApis.addnew_info + teon_id + "/" + "5";

        if (villageRequest == null) {
            villageRequest = new VillageRequest();
        }

        Log.i("村级列表", "url: " + addnew_url);
        HttpUtils.requestGet(_mActivity, addnew_url, villageRequest);
    }


    private class ContyRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            Log.i("乡级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();

            contylist = JsonUtil.json2Collection(jsonStr, type);

            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            Log.i("乡级列表", "error: " + error);

            cancelLoadingDialog();
        }
    }

    private class TwonRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            Log.i("县级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();

            twonlist = JsonUtil.json2Collection(jsonStr, type);

            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            Log.i("县级列表", "error: " + error);

            cancelLoadingDialog();
        }
    }

    private class VillageRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);

            Log.i("村级列表", "success: " + jsonStr);

            Type type = new TypeToken<ArrayList<CountyEntity>>() {
            }.getType();

            villagelist = JsonUtil.json2Collection(jsonStr, type);

            cancelLoadingDialog();
        }

        @Override
        public void error(String error) {
            super.error(error);
            Log.i("村级列表", "error: " + error);

            cancelLoadingDialog();
        }
    }


    /**
     * 监听
     */
    private void initListener() {

        //---------applyRvAdapter条目点击---------------------------
        //applyRvAdapter条目点击事件-->点击整个条目,adapter中,子view不用addonclicklinstener
        applyRvAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArrayList<ReBuildItemEntity.DataBean> list = (ArrayList<ReBuildItemEntity.DataBean>) adapter.getData();
                ReBuildItemEntity.DataBean rowsBean = list.get(position);
                if (rowsBean != null) {
                    UserEntity userEntity = SPUtil.getBeanValue(Constants.KEY_USER, UserEntity.class);
                    if (userEntity != null) {
                        //根据重建状态选择跳转的是页面是否能进行编辑还是预览
                        switch (rowsBean.getJiancha_result_n()) {
                            case "合格":
                                //不可进行编辑
                                rowsBean.setEdit(false);
                                EventBus.getDefault().post(new StartNewFragmentEvent(ToiletRebuildDetialFragment.newInstance(rowsBean)));
                                break;

                            case "不合格":
                            case "未检查":

                                //只能是乡/村级别
                                if ("303".equals(userEntity.getOpt_level())
                                        || "304".equals(userEntity.getOpt_level())) {
                                    rowsBean.setEdit(true);
                                    EventBus.getDefault().post(new StartNewFragmentEvent(ToiletRebuildDetialFragment.newInstance(rowsBean)));

                                } else {
                                    rowsBean.setEdit(false);
                                    EventBus.getDefault().post(new StartNewFragmentEvent(ToiletRebuildDetialFragment.newInstance(rowsBean)));
                                }
                                break;

                            default:

                                break;
                        }
                    }
                }
            }
        });

        //---------列表的刷新---------------------------
        // buytoiletfilesTrefresh刷新
        rebuildRvTrefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                Log.e("显示", "refresh");

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("显示", "refreshRun");
//                        mBuyAdapter.removeAllFooterView();

                        //清空集合
                        if (params!=null){
                            params.clear();
                        }

                        requestRefresh();
                    }
                }, 2000);
            }

            @Override
            public void onFinishRefresh() {
                super.onFinishRefresh();
                Log.e("显示", "Finishrefresh");
                applyRvAdapter.setEnableLoadMore(true);

            }
        });

        //预加载
        applyRvAdapter.setPreLoadNumber(Constant.PRE_SIZE);

        //设置动画
        applyRvAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);

        //applyRvAdapter加载数据的监听
        applyRvAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                int currentSize = applyRvAdapter.getData().size();
                if (!TextUtils.isEmpty(mTotalSize)) {

                    int totalSize = Integer.parseInt(mTotalSize);
                    if (currentSize >= totalSize) {
                        applyRvAdapter.loadMoreEnd();
                    } else {
                        index++;

                        loadMoreData(index * pageSize, pageSize);
                    }
                }

            }
        }, rebuildRv);

    }


    private Map<String, String> params = new TreeMap<>();

    @OnClick({R.id.tv_default_rebuild_order, R.id.bt_rebuild_filter,
            R.id.rebuild_address_conty, R.id.rebuild_address_town,
            R.id.rebuild_address_village,R.id.bt_rebuild_top})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            //返回顶部
            case R.id.bt_rebuild_top:

                rebuildRv.smoothScrollToPosition(0);

                break;

            case R.id.tv_default_rebuild_order:
                ListPopupWindow userPopupWindow = new ListPopupWindow(_mActivity);
                setPopuData(view, userPopupWindow, userorderlist);
                setPopuClickListener(new PopuClickListener() {
                    @Override
                    public void show(String mess) {
                        tvDefaultRebuildOrder.setText(mess);
                        switch (mess) {
                            case "辖区单位":
                                etRebuildGetcontent.setVisibility(View.GONE);
                                rebuildSearchAll.setVisibility(View.VISIBLE);
                                break;
                            case "户  编  号":
                            case "户     名":
                                etRebuildGetcontent.setVisibility(View.VISIBLE);
                                rebuildSearchAll.setVisibility(View.GONE);
                                break;
                            default:

                                break;
                        }
                    }
                });
                break;


            case R.id.rebuild_address_conty:

                contyPopupWindow = new ListPopupWindow(_mActivity);
                setPopuDataList(view, contyPopupWindow, contylist);
                setPopuClickListenerList(new ContyPopuListener() {
                    @Override
                    public void show(CountyEntity Centity, String text) {
                        rebuild_Tvconty.setText(Centity.getText());
                        showLoadingDialog("正在加载乡镇数据");
                        SPUtil.putString(Constants.CONTY_LEVEL, "xian");
                        SPUtil.putString(Constants.CONTY_ID, Centity.getValue());
                        getTownList(Centity.getValue());


                    }
                });

                break;
            case R.id.rebuild_address_town:
                String conty_address = rebuild_Tvconty.getText().toString().trim();
                if (TextUtils.isEmpty(conty_address) || "县".equals(conty_address)) {
                    showShortToast("请先选择县级单位");
                    return;
                } else {
                    try {
                        if (twonlist != null && twonlist.size() > 0) {
                            twonPopupWindow = new ListPopupWindow(_mActivity);
                            setPopuDataList(view, twonPopupWindow, twonlist);
                            setPopuClickListenerList(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {

                                    rebuild_Tvtown.setText(Centity.getText());
                                    SPUtil.putString(Constants.CONTY_LEVEL, "xiang");
                                    SPUtil.putString(Constants.CONTY_ID, Centity.getValue());
                                    showLoadingDialog("正在加载村级数据");
                                    getVillageList(Centity.getValue());

                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.i("list为null", "乡级列表onViewClicked: " + e.toString());
                    }

                }

                break;
            case R.id.rebuild_address_village:

                String town_address = rebuild_Tvtown.getText().toString().trim();
                if (TextUtils.isEmpty(town_address) || "乡(镇)".equals(town_address)) {
                    showShortToast("请先选择乡级单位");
                    return;
                } else {

                    try {
                        if (villagelist != null && villagelist.size() > 0) {
                            villagePopupWindow = new ListPopupWindow(_mActivity);
                            setPopuDataList(view, villagePopupWindow, villagelist);
                            setPopuClickListenerList(new ContyPopuListener() {
                                @Override
                                public void show(CountyEntity Centity, String text) {
                                    rebuild_Tvvillage.setText(Centity.getText());
                                    SPUtil.putString(Constants.CONTY_LEVEL, "cun");
                                    SPUtil.putString(Constants.CONTY_ID, Centity.getValue());
                                }
                            });
                        }
                    } catch (Exception e) {
                        Log.i("list为null", "村级列表onViewClicked: " + e.toString());

                    }
                }
                break;

            case R.id.bt_rebuild_filter:

                String tv_condition = tvDefaultRebuildOrder.getText().toString().trim();
                if (TextUtils.isEmpty(tv_condition) || "条件".equals(tv_condition)) {
                    showShortToast("请先选择条件");
                    return;
                }

                //etRebuildGetcontent
                String et_contant = etRebuildGetcontent.getText().toString().trim();
                if ("户     名".equals(tv_condition) || "户  编  号".equals(tv_condition)) {
                    if (TextUtils.isEmpty(et_contant) || "请输入检索内容".equals(et_contant)) {
                        showShortToast("请确定查询内容");
                        return;
                    }
                } else if ("辖区单位".equals(tv_condition)) {
                    String conty_tv = rebuild_Tvconty.getText().toString().trim();
                    if ("县".equals(conty_tv)) {
                        showShortToast("请确定查询级别");
                        return;
                    }
                }
                switch (tv_condition) {
                    case "户     名":
                        params.put("huming", et_contant);
                        break;
                    case "户  编  号":
                        params.put("hubianhao", et_contant);
                        break;
                    case "辖区单位":
                        String conty_level = SPUtil.getString(Constants.CONTY_LEVEL, "");
                        if (!TextUtils.isEmpty(conty_level)) {
                            if ("xian".equals(conty_level)) {
                                if (params.containsKey("a.xiang_area_id")) {
                                    params.remove("a.xiang_area_id");
                                }
                                if (params.containsKey("a.area_id")) {
                                    params.remove("a.area_id");
                                }
                                params.put("a.xian_area_id", SPUtil.getString(Constants.CONTY_ID, ""));
                            } else if ("xiang".equals(conty_level)) {
                                if (params.containsKey("a.xian_area_id")) {
                                    params.remove("a.xian_area_id");
                                }
                                if (params.containsKey("a.area_id")) {
                                    params.remove("a.area_id");
                                }
                                params.put("a.xiang_area_id", SPUtil.getString(Constants.CONTY_ID, ""));
                            } else if ("cun".equals(conty_level)) {
                                if (params.containsKey("a.xian_area_id")) {
                                    params.remove("a.xian_area_id");
                                }
                                if (params.containsKey("a.xiang_area_id")) {
                                    params.remove("a.xiang_area_id");
                                }
                                params.put("a.area_id", SPUtil.getString(Constants.CONTY_ID, ""));
                            }
                        }
                        break;

                    default:

                        break;
                }

                syso(params);
                Log.i("检索数据", "onViewClicked: " + SPUtil.getString(Constants.CONTY_LEVEL, "") + "~~" + SPUtil.getString(Constants.CONTY_ID, ""));

                //根据条件筛选重建列表
                getConditionSearCh(params);
                break;
        }
    }

    //模拟输出测验
    private void syso(Map<String, String> conditionmap) {
        Set<Map.Entry<String, String>> entrySet = conditionmap.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> me = iterator.next();
            String key = me.getKey();
            String value = me.getValue();
            Log.i("conditionmap", key + ":" + value);
        }

    }

//====================listpopuwindow  县 村=======================================

    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalists
     */

    private void setPopuDataList(View view, final ListPopupWindow mPopupWindow, final List<CountyEntity> datalists) {

        //清空集合,添加数据
        namelist.clear();
        for (CountyEntity ce : datalists) {
            namelist.add(ce.getText());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, namelist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        // mPopupWindow.setAnchorView(view);
        mPopupWindow.setAnchorView(rebuildMD);

        mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 12));

//        mPopupWindow
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListenerList != null) {
                    popuClickListenerList.show(datalists.get(position), datalists.get(position).getText());
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();


    }

    public ContyPopuListener popuClickListenerList;

    public void setPopuClickListenerList(ContyPopuListener popuClickListenerList) {
        this.popuClickListenerList = popuClickListenerList;
    }
//--------------------------------------------------------------------------------------


    /**
     * 根据条件筛选重建列表
     */
    private void getConditionSearCh(Map<String, String> params) {
        index = 0;
        loadConditionData(params, index, pageSize);
    }

    /**
     * eventbus 页面跳转,事件接受
     *
     * @param messageEvent
     */
    @Subscribe
    public void onEventReceive(MessageEvent messageEvent) {

        if ("361".equals(messageEvent.getMessage())) {
            //提交成功
            LogUtils.e("显示", "刷新");
            new Handler() {
            }.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestRefresh();
                }
            }, 500);
        }
    }

    //Rv一次性加载多少个条目
    private int pageSize = 5;

    /**
     * 页面条转过来就刷新数据
     */
    private void requestRefresh() {
        Log.e("显示", "指示refresh " + index);
        applyRvAdapter.setEnableLoadMore(false);
        buyItemList.clear();
        applyRvAdapter.setNewData(buyItemList);

        if (rebuildRvTrefresh != null) {
            rebuildRvTrefresh.finishRefreshing();
        }
        index = 0;
        loadMoreData(index, pageSize);
    }

    /**
     * 页面加载动画结束就调用  loadMoreData(index, pageSize);
     * 所以  将两个方法紧挨着
     *
     * @param savedInstanceState
     */
    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        //添加家在逻辑
        Log.e("显示", "指示enter " + index);

        loadMoreData(index, pageSize);
    }

    /**
     * 加载数据
     *
     * @param index    页数
     * @param pageSize
     */
    private void loadMoreData(int index, int pageSize) {

        if (index == 0) {
            showLoadingDialog();
        }
        //page=1&rows=10  rebuildhomemenu_check
        String rebuildUrl = HttpApis.rebuildDetial_item;
        Log.e("重建", rebuildUrl);
        if (rebuildRequest == null) {
            rebuildRequest = new RebuildDataItemRequest();
        }

        Map<String, String> map = new HashMap<>();
        map.put("iud", rebuildhomemenu_check.getIud());
        map.put("start", String.valueOf(index));
        map.put("pagesize", String.valueOf(pageSize));
        HttpUtils.requestGet(_mActivity, rebuildUrl, map, rebuildRequest);

    }

    private void loadConditionData(Map<String, String> param, int index, int pageSize) {

        if (index == 0) {
            showLoadingDialog();
        }
        //page=1&rows=10  rebuildhomemenu_check
        String rebuildUrl = HttpApis.rebuildDetial_item;
        Log.e("重建", rebuildUrl);
        if (rebuildRequest == null) {
            rebuildRequest = new RebuildDataItemRequest();
        }

        Map<String, String> map = new HashMap<>();
        map.put("iud", rebuildhomemenu_check.getIud());
        map.put("start", String.valueOf(index));
        map.put("pagesize", String.valueOf(pageSize));

        if (params != null) {
            map.putAll(param);
        }

        HttpUtils.requestGet(_mActivity, rebuildUrl, map, rebuildRequest);

    }

    //请求列表数据
    private class RebuildDataItemRequest extends Request {
        @Override
        public void success(String jsonStr) {
            super.success(jsonStr);
            //这里是假数据

            Log.i("重建条目信息", "success" + jsonStr);
            ReBuildItemEntity rebuildItemEntity = GsonTools.changeGsonToBean(jsonStr, ReBuildItemEntity.class);
            //将数据解析出来
            if (rebuildItemEntity != null) {
                processData(rebuildItemEntity);
            }
            applyRvAdapter.loadMoreComplete(); //加载完

            etRebuildGetcontent.setText("");
            rebuild_Tvconty.setText("县");
            rebuild_Tvtown.setText("乡(镇)");
            rebuild_Tvvillage.setText("村");
            params.clear();

            cancelLoadingDialog();


        }

        @Override
        public void error(String error) {
            super.error(error);
            Log.i("重建条目信息", "error" + error);
            if (index == 0 || !NetworkUtils.isConnected(_mActivity)) {
                applyRvAdapter.setEmptyView(errorView);
            } else {
                applyRvAdapter.setEmptyView(emptyView);
                applyRvAdapter.loadMoreFail();
            }

            if (index == 0) {
                cancelLoadingDialog();
            }
        }
    }

    //临时存放此处
    private String mTotalSize;

    /**
     * 讲解析出来的数据,进行加载
     *
     * @param rebuildItemEntity
     */
    private void processData(ReBuildItemEntity rebuildItemEntity) {
        LogUtils.e("显示", "指示process " + index);

        if (rebuildItemEntity != null) {
            mTotalSize = rebuildItemEntity.getRecordsTotal();
            if (Integer.parseInt(mTotalSize) > 0) {
                if (index == 0) {
                    //设置新数据
                    applyRvAdapter.setNewData(rebuildItemEntity.getData());
                } else {
                    applyRvAdapter.addData(rebuildItemEntity.getData());
                }
            } else {
                applyRvAdapter.setNewData(null);
                applyRvAdapter.setEmptyView(emptyView);
            }
            LogUtils.e("显示", "数据u" + applyRvAdapter.getData().size());
        } else {
            applyRvAdapter.setEmptyView(emptyView);
        }

    }


    //-------------------------------------------------------------------------

    /**
     * 显示listpopuwindow,并使用回调,显示数据
     *
     * @param view
     * @param mPopupWindow
     * @param datalist
     */
    private void setPopuData(View view, final ListPopupWindow mPopupWindow, final List<String> datalist) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(_mActivity, android.R.layout.simple_list_item_1, datalist);
        mPopupWindow.setAdapter(adapter);

        //弹出的位置  弹出锚点
        //mPopupWindow.setAnchorView(view);
        mPopupWindow.setAnchorView(rebuildMD);


        mPopupWindow.setVerticalOffset(ConvertUtils.dp2px(_mActivity, 12));
        //设置宽高
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);

        mPopupWindow.setModal(true);//设置模态框，设置为true响应物理键
        //设置条目点击事件
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //使用回调,显示数据
                if (popuClickListener != null) {
                    popuClickListener.show("" + datalist.get(position));
                }
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.show();
    }

    //-------------设置popu传值接口-----------------------------------------------------------
    public PopuClickListener popuClickListener;

    public void setPopuClickListener(PopuClickListener popuClickListener) {
        this.popuClickListener = popuClickListener;
    }
//--------------------------------------------------------------------------------------


    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if (params != null) {
            params.clear();
        }

        unbinder.unbind();
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
        cancelLoadingDialog();
    }


}
